package com.jiawa.train.member.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiawa.train.common.req.MemberTicketReq;
import com.jiawa.train.common.resp.PageResp;
import com.jiawa.train.member.domain.po.Ticket;
import com.jiawa.train.member.mapper.TicketMapper;
import com.jiawa.train.member.req.TicketQueryReq;
import com.jiawa.train.member.resp.TicketQueryResp;
import com.jiawa.train.member.service.ITicketService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 车票 服务实现类
 * </p>
 *
 * @author hrz
 * @since 2025-09-09
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class TicketServiceImpl extends ServiceImpl<TicketMapper, Ticket> implements ITicketService {

    /**
     * 会员购买车票后新增保存
     *
     * @param req
     */
    public void save(MemberTicketReq req) throws Exception {
        Ticket ticket = BeanUtil.copyProperties(req, Ticket.class);
        ticket.setCreateTime(LocalDateTime.now());
        ticket.setUpdateTime(LocalDateTime.now());
        this.save(ticket);
    }

    public PageResp<TicketQueryResp> queryList(TicketQueryReq req) {

        log.info("查询页码：{}", req.getPage());
        log.info("每页条数：{}", req.getSize());
        Page<Ticket> page = new Page<>();
        if(ObjectUtil.isNotEmpty(req.getMemberId())){
            //会员端
            page = this.lambdaQuery()
                    .eq(Ticket::getMemberId, req.getMemberId())
                    .orderByDesc(Ticket::getId)
                    .page(new Page<>(req.getPage(), req.getSize()));
        }else{
            //管理端
            page = this.lambdaQuery()
                    .orderByDesc(Ticket::getId)
                    .page(new Page<>(req.getPage(), req.getSize()));
        }
        log.info("总行数：{}", page.getTotal());
        log.info("总页数：{}", page.getPages());
        List<Ticket> records = page.getRecords();
        List<TicketQueryResp> list = BeanUtil.copyToList(records, TicketQueryResp.class);

        PageResp<TicketQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(page.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    public void delete(Long id) {
        this.removeById(id);
    }
}
